import boto3, json, uuid
from django.shortcuts import render, redirect
from django.conf import settings
from django.apps import apps
from django.http import JsonResponse,HttpResponse
from .utils import getTempUrl
from django.views.decorators.csrf import csrf_exempt


def getDownloadUrl(req):
    '下载链接响应方法'
    filename = req.GET.get("filepath")
    if filename.startswith("/"):
        filename = filename[1:]
    tempDownloadUrl = getTempUrl(filename, "get_object")
    return redirect(tempDownloadUrl)

@csrf_exempt
def getUploadUrl(req):
    data = json.loads(req.body)
    filename = data.get("filename") # TODO: 限制文件名长度, 然后改为char?

    field_name = data.get("field_name")
    model_name = data.get("model_name")

    try:
        model = apps.get_model(model_name)
        field = model._meta.get_field(field_name)
        upload_to = field.upload_to # 这里有点折腾, 但是不能信任前端传递upload_to, 未来这里可以取max_size等其他参数.
    except Exception:
        HttpResponse(f"no such model {model_name} or field {field_name}")

    if ".." in filename:
        return HttpResponse("失败, 文件名中含有..")
    if "." not in filename:
        filename = filename + "."
    unique_filename = ".".join([
        filename.split(".")[0],
        str(uuid.uuid4()),
        filename.split(".")[-1]
    ])
    value = f'{upload_to}/{unique_filename}'
    resp = getTempUrl(value, "put_object")

    return JsonResponse({
        "value":value,
        "url":resp,
    })